package com.share.lagou.decoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;

/**
 * @author caifan
 * @since 2022/7/18
 */
public class EchoServer {

    public static void main(String[] args) throws Exception {
        new EchoServer().startEchoServer(9011);
    }

    public void startEchoServer(int port) throws Exception {
        final EventLoopGroup bossGroup = new NioEventLoopGroup();
        final EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 固定长度解码器
                            ch.pipeline().addLast(new FixedLengthFrameDecoder(10))
                                         .addLast(new ResponseSampleEncoder())
                                         .addLast(new RequestSampleHandler());

                            // 设置分隔符为 & 最大长度为10 ，超过则抛错的解码器
//                            final ByteBuf delimiter = Unpooled.copiedBuffer("&".getBytes());
//                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(10, true, true, delimiter))
//                                        .addLast(new EchoServerHandler());
                        }
                    });
            final ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
